import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/core/gitcode_api.dart';
import 'package:gitcode_pocket_tool/core/app_theme.dart';
import 'dart:async';
import 'package:gitcode_pocket_tool/core/app_config.dart';

class OrganizationsPage extends StatefulWidget {
  const OrganizationsPage({super.key});

  @override
  State<OrganizationsPage> createState() => _OrganizationsPageState();
}

class _OrganizationsPageState extends State<OrganizationsPage> {
  final GitCodeApiClient _apiClient = GitCodeApiClient();
  List<GitCodeOrganization> _organizations = [];
  bool _isLoading = false;
  String? _errorMessage;
  int _currentPage = 1;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadOrganizations();
  }

  Future<void> _loadOrganizations() async {
    if (_isLoading || (!_hasMore && _currentPage > 1)) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 使用新的API方法获取gitcode用户所属的组织列表
      final newOrganizations = await _apiClient.getOrganizations(
        username: 'gitcode', // 获取gitcode用户所属的组织
        personalToken: AppConfig.demoToken,
        perPage: 10,
        page: _currentPage,
      );

      setState(() {
        if (_currentPage == 1) {
          _organizations = newOrganizations;
        } else {
          _organizations.addAll(newOrganizations);
        }

        _hasMore = newOrganizations.length == 10;
        _currentPage++;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget _buildOrganizationItem(GitCodeOrganization org) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            CircleAvatar(
              backgroundImage: NetworkImage(org.avatarUrl),
              radius: 32,
              backgroundColor: AppTheme.surfaceColor,
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    org.login,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  if (org.name != null && org.name!.isNotEmpty) ...[
                    Text(
                      org.name!,
                      style: TextStyle(color: AppTheme.textSecondary),
                    ),
                  ],
                  if (org.description != null) ...[
                    const SizedBox(height: 8),
                    Text(
                      org.description!,
                      style: TextStyle(
                          color: AppTheme.textSecondary, fontSize: 14),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                  if (org.membersCount != null) ...[
                    const SizedBox(height: 8),
                    Text(
                      '${org.membersCount} 名成员',
                      style: TextStyle(
                          color: AppTheme.textSecondary, fontSize: 14),
                    ),
                  ],
                ],
              ),
            ),
            const Icon(Icons.chevron_right, color: AppTheme.textSecondary),
          ],
        ),
      ),
    );
  }

  Future<void> _refresh() async {
    // 重置状态并重新加载数据
    setState(() {
      _currentPage = 1;
      _hasMore = true;
      _organizations = [];
    });
    await _loadOrganizations();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('组织'),
        elevation: 4,
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : _errorMessage != null
                ? ListView(
                    children: [
                      Center(
                        child: Padding(
                          padding: const EdgeInsets.all(32),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const Icon(Icons.error_outline,
                                  size: 48, color: AppTheme.errorColor),
                              const SizedBox(height: 16),
                              Text(
                                _errorMessage!,
                                textAlign: TextAlign.center,
                                style: TextStyle(color: AppTheme.textSecondary),
                              ),
                              const SizedBox(height: 16),
                              ElevatedButton(
                                onPressed: _refresh,
                                child: const Text('重试'),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                : _organizations.isEmpty
                    ? ListView(
                        children: [
                          Center(
                            child: Padding(
                              padding: const EdgeInsets.all(32),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const Icon(Icons.group_off,
                                      size: 48, color: AppTheme.textSecondary),
                                  const SizedBox(height: 16),
                                  Text(
                                    '暂无组织数据',
                                    style: TextStyle(
                                        color: AppTheme.textSecondary),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      )
                    : NotificationListener<ScrollNotification>(
                        onNotification: (notification) {
                          if (notification is ScrollEndNotification &&
                              notification.metrics.extentAfter == 0 &&
                              _hasMore &&
                              !_isLoading) {
                            _loadOrganizations();
                          }
                          return true;
                        },
                        child: ListView.builder(
                          itemCount: _organizations.length + (_hasMore ? 1 : 0),
                          itemBuilder: (context, index) {
                            if (index == _organizations.length) {
                              return _isLoading
                                  ? const Center(
                                      child: CircularProgressIndicator())
                                  : const SizedBox();
                            }
                            return _buildOrganizationItem(
                                _organizations[index]);
                          },
                        ),
                      ),
      ),
    );
  }
}
